using UnityEngine;

namespace Render
{
    public static class Geometry
    {
        public static void CreateQuad(int trisX, int trisZ, out Vector3[] vertices, out int[] indices, out Vector2[] uvs)
        {
            int vertexCount = (trisX+1)*(trisZ+1);
            int indexCount = trisX*trisZ*6;

            vertices = new Vector3[vertexCount];
            indices = new int[indexCount];
            uvs = new Vector2[vertexCount];

            float maxX = trisX*1.0f;
            float maxZ = trisZ*1.0f;
            float u, v;

            int vertex = 0, index = 0, uv = 0;
            int indexBase = 0;
            int indexRow = trisX+1;

            for (int z=0; z<=trisZ; ++z)
            {
                for (int x=0; x<=trisX; ++x)
                {
                    u = x/maxX;
                    v = z/maxZ;

                    vertices[vertex].x = u-0.5f;
                    vertices[vertex].z = v-0.5f;
                    vertices[vertex].y = 0.0f;
                    vertex++;

                    if (x!=trisX && z!=trisZ)
                    {
                        indexBase = x+z*indexRow;

                        indices[index++] = indexBase;
                        indices[index++] = indexBase+indexRow;
                        indices[index++] = indexBase+indexRow+1;
                        indices[index++] = indexBase;
                        indices[index++] = indexBase+indexRow+1;
                        indices[index++] = indexBase+1;
                    }

                    uvs[uv].x = u;
                    uvs[uv].y = v;
                    uv++;
                }
            }
        }
    }
}